//
//  AppDelegate+HREase.m
//  Hear
//
//  Created by mac on 2017/3/28.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "AppDelegate+HREase.h"

#import "HearNavigationController.h"
#import "HRPhoneLoginViewController.h"
#import "EaseSDKHelper.h"
//#import "MyPlayTool.h"
#import "HRAnswerListViewController.h"
#import "HRTabBarViewController.h"
#import "EBForeNotification.h"
#import "HRRecordAudioViewController.h"
#import "HRGuideViewController.h"
#import "DHGuidePageHUD.h"

static NSString *kMessageType = @"MessageType";
static NSString *kConversationChatter = @"ConversationChatter";

static const CGFloat kDefaultPlaySoundInterval = 3.0;

@implementation AppDelegate (HREase)
- (void)easemobApplication:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
                    appkey:(NSString *)appkey
              apnsCertName:(NSString *)apnsCertName
               otherConfig:(NSDictionary *)otherConfig
{
    //注册登录状态监听
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(loginStateChange:)
                                                 name:KNOTIFICATION_LOGINCHANGE
                                               object:nil];
    
    
    [[EaseSDKHelper shareHelper] hyphenateApplication:application
                        didFinishLaunchingWithOptions:launchOptions
                                               appkey:appkey
                                         apnsCertName:apnsCertName
                                          otherConfig:@{@"httpsOnly":[NSNumber numberWithBool:NO], kSDKConfigEnableConsoleLogger:[NSNumber numberWithBool:YES],@"easeSandBox":[NSNumber numberWithBool:NO]}];
    
    BOOL isAutoLogin = [EMClient sharedClient].isAutoLogin;
    if (isAutoLogin){
        [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@YES];
    }
    else{
        [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
    }
    
    
    
    
    
    [[EMClient sharedClient] addDelegate:self delegateQueue:nil];
    
    //注册消息回调
    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickBannerView:) name:EBBannerViewDidClick object:nil];

    

    
    // 音视频配置
    EMCallOptions *options = [[EMClient sharedClient].callManager getCallOptions];
    //当对方不在线时，是否给对方发送离线消息和推送，并等待对方回应
    options.isSendPushIfOffline = NO;
    [[EMClient sharedClient].callManager setCallOptions:options];

}



-(void)clickBannerView:(NSNotification*)noti{
    DDLog(@"ddd,%@",noti);
    
    NSDictionary *extDict = noti.object[@"aps"][@"easeExt"];

    

    EaseMessageViewController *messgaeVC = [[EaseMessageViewController alloc] initWithConversationChatter:noti.object[@"aps"][@"userID"] conversationType:EMConversationTypeChat];
    messgaeVC.otherNickNameStr = extDict[@"otherNickName"];
    messgaeVC.otherIconStr = extDict[@"otherIconColor"];
    messgaeVC.otherIconName = extDict[@"otherIcon"];
    messgaeVC.title = extDict[@"otherNickName"];
    [VIEWCCONTROLER.navigationController pushViewController:messgaeVC animated:YES];
    
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadTabItemBageCountNotifi" object:nil];

    
    
}


- (void)easemobApplication:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    [[EaseSDKHelper shareHelper] hyphenateApplication:application didReceiveRemoteNotification:userInfo];

    [EBForeNotification handleRemoteNotification:userInfo soundID:1312 isIos10:NO];

}


#pragma -mark-接收消息回调
- (void)didReceiveMessages:(NSArray *)aMessages
{
//    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"newMessageNotifi"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"newMesageNotifi" object:nil];

    [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadTabItemBageCountNotifi" object:nil];

    
    BOOL isRefreshCons = YES;
    for(EMMessage *message in aMessages){
//        BOOL needShowNotification = (message.chatType != EMChatTypeChat) ? [self _needShowNotification:message.conversationId] : YES;
        
        UIApplicationState state = [[UIApplication sharedApplication] applicationState];
        if(state == UIApplicationStateBackground){
            if ([[NSUserDefaults standardUserDefaults] boolForKey:@"easemobSwitch"]) return;
            [self showNotificationWithMessage:message];
        }else if (state == UIApplicationStateActive){
            [self showNotificationWithMessage:message];

            // 收到消息时，播放音频
//            [[EMCDDeviceManager sharedInstance] playNewMessageSound];
            // 收到消息时，震动
//            [[EMCDDeviceManager sharedInstance] playVibration];
        }
    }
    
    
   
}

#pragma -mark-接收透传消息回调
- (void)didReceiveCmdMessages:(NSArray *)aCmdMessages
{
    //    EMMessage *message = aCmdMessages.lastObject;
    for (EMMessage *message in aCmdMessages)
    {
        EMMessageBody *msgBody = message.body;
        if (msgBody.type == EMMessageBodyTypeCmd)
        {
            
            
        }
    }
}




- (void)userAccountDidLoginFromOtherDevice{
    EMError *error = [[EMClient sharedClient] logout:YES];
    if (!error) {
        DDLog(@"==========退出环信成功");
    }
    HearNavigationController *nav = [[HearNavigationController alloc] initWithRootViewController:[HRPhoneLoginViewController new]];
    
    self.window.rootViewController = nav;
    
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [MBProgressHUD showMessage:@"您的账号在另一台设备登陆" finishBlock:nil];
    });
}

/*
 *  当前登录账号在其它设备登录时会接收到该回调
 */
//- (void)didLoginFromOtherDevice
//{
//    [[MyPlayTool sharePlayTool] stop];

//    EMError *error = [[EMClient sharedClient] logout:YES];
//    if (!error) {
//        DDLog(@"==========退出环信成功");
//    }
//     HearNavigationController *nav = [[HearNavigationController alloc] initWithRootViewController:[HRPhoneLoginViewController new]];
//
//    self.window.rootViewController = nav;
//
//
//
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [MBProgressHUD showMessage:@"您的账号在另一台设备登陆" finishBlock:nil];
//    });
//}

- (void)didRemovedFromServer
{
//    [[MyPlayTool sharePlayTool] stop];

    HearNavigationController *nav = [[HearNavigationController alloc] initWithRootViewController:[HRPhoneLoginViewController new]];

    
    self.window.rootViewController = nav;
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [MBProgressHUD showMessage:@"你的账号已被从服务器端移除" finishBlock:nil];
    });
    
}

// 将得到的deviceToken传给SDK
- (void)easemobApplication:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[EMClient sharedClient] bindDeviceToken:deviceToken];
    });
}
// 注册deviceToken失败，此处失败，与环信SDK无关，一般是您的环境配置或者证书配置有误
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"apns.failToRegisterApns", Fail to register apns)
                                                    message:error.description
                                                   delegate:nil
                                          cancelButtonTitle:NSLocalizedString(@"ok", @"OK")
                                          otherButtonTitles:nil];
    [alert show];
}

- (void)ease_application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    NSDictionary * userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if(userInfo){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:@"ease_MessageuserInfo" object:nil userInfo:userInfo];
        });
    }else{
        [MBProgressHUD showMessage:@"登录过期" finishBlock:nil];

    }
}

- (void)loginStateChange:(NSNotification *)notification {
    BOOL loginSuccess = [notification.object boolValue];
    if (loginSuccess)//登陆成功加载主窗口控制器
    {
        self.window.rootViewController = [[HRTabBarViewController alloc] init];
    }else{
        if ([[NSUserDefaults standardUserDefaults] boolForKey:BOOLFORKEY]){
            HearNavigationController *nav = [[HearNavigationController alloc] initWithRootViewController:[HRPhoneLoginViewController new]];//HRGuideViewController
            self.window.rootViewController = nav;
        }else{
            HearNavigationController *nav = [[HearNavigationController alloc] initWithRootViewController:[HRGuideViewController new]];//HRGuideViewController
            self.window.rootViewController = nav;
        }
        
    }
}

- (void)easamobApplication:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
    
    
    NSDictionary *userInfo = notification.userInfo;
    NSString *values = userInfo[@"values"];
    if (application.applicationState == UIApplicationStateBackground) {
//        [VIEWCCONTROLER.navigationController pushViewController:[HRAnswerListViewController new] animated:YES];
        
    }
    else if(application.applicationState == UIApplicationStateInactive)//杀死状态下，直接跳转到跳转页面。
    {
//        [VIEWCCONTROLER.navigationController pushViewController:[HRAnswerListViewController new] animated:YES];
        

    }else{

    }
    
    
}





- (void)showNotificationWithMessage:(EMMessage *)message
{
    EMPushOptions *options = [[EMClient sharedClient] pushOptions];
    NSString *alertBody = nil;
    EMMessageBody *messageBody = message.body;
    NSString *messageStr = nil;
    UIApplication *application = [UIApplication sharedApplication];

    if (options.displayStyle == EMPushDisplayStyleMessageSummary || application.applicationState == UIApplicationStateActive) {
        switch (messageBody.type) {
            case EMMessageBodyTypeText:
            {
                messageStr = ((EMTextMessageBody *)messageBody).text;
            }
                break;
            case EMMessageBodyTypeImage:
            {
                messageStr = NSLocalizedString(@"message.image", @"Image");
            }
                break;
            case EMMessageBodyTypeLocation:
            {
                messageStr = NSLocalizedString(@"message.location", @"Location");
            }
                break;
            case EMMessageBodyTypeVoice:
            {
                messageStr = NSLocalizedString(@"message.voice", @"Voice");
            }
                break;
            case EMMessageBodyTypeVideo:{
                messageStr = NSLocalizedString(@"message.video", @"Video");
            }
                break;
            default:
                break;
        }
    }
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
    [userInfo setObject:[NSNumber numberWithInt:message.chatType] forKey:kMessageType];
    [userInfo setObject:message.conversationId forKey:kConversationChatter];
    
        

    
    
    //发送本地推送
    if (NSClassFromString(@"UNUserNotificationCenter")) {
        
        NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
        NSInteger unreadCount = 0;
        for (EMConversation *conversation in conversations) {
            unreadCount += conversation.unreadMessagesCount;
        }
        
        
        if (application.applicationState == UIApplicationStateActive) {
            id rootVC = [[UIApplication sharedApplication].keyWindow rootViewController];
            if ([rootVC isKindOfClass:[HearNavigationController class]])return;
            EaseMessageViewController *currentVC = VIEWCCONTROLER;
            
            if ([VIEWCCONTROLER isKindOfClass:[EaseMessageViewController class]]){
                if([(id)currentVC.conversation.conversationId isEqualToString:message.conversationId])return;
            }
            
            
            NSString *otherNickName =@"";
            NSString *otherIcon =@"";
            NSString *otherIconColor =@"";
            
            
            if (message.direction == EMMessageDirectionSend){
                otherNickName = message.ext[@"otherNickName"];
                
                otherIcon =message.ext[@"otherIcon"];
                otherIconColor = message.ext[@"otherIconColor"];
            }else{
                otherNickName = message.ext[@"nickName"];
                
                otherIcon = message.ext[@"icon"];
                otherIconColor = message.ext[@"iconColor"];
            }
            
            NSMutableDictionary *extDict = message.ext;
            extDict[@"otherNickName"] = otherNickName;
            extDict[@"otherIcon"] = otherIcon;
            extDict[@"otherIconColor"] = otherIconColor;


            
            [EBForeNotification handleRemoteNotification:@{@"aps":@{@"alert":messageStr, @"sound":@"sound",@"badge":[NSString stringWithFormat:@"%d",unreadCount],@"userID":message.conversationId,@"easeExt":extDict}} soundID:1312 isIos10:NO];
            return;
        }

        UILocalNotification *notification = [[UILocalNotification alloc] init];
        notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:0.1]; //触发通知的时间
        notification.alertBody = @"你收到一条消息";
        notification.alertAction = NSLocalizedString(@"open", @"Open");
        notification.timeZone = [NSTimeZone defaultTimeZone];
        notification.soundName = UILocalNotificationDefaultSoundName;


        notification.applicationIconBadgeNumber = unreadCount;
        notification.userInfo = userInfo;
        

        //发送通知
        [[UIApplication sharedApplication] scheduleLocalNotification:notification];
        
    }
}






@end
